package org.sang.service;

import com.alibaba.fastjson.JSON;
import org.sang.mapper.ExamAnswerMapper;
import org.sang.mapper.ExamQuestionMapper;
import org.sang.pojo.RespBean;
import org.sang.pojo.dto.ExamAnswerDTO;
import org.sang.pojo.dto.ExamQuestionDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 面试题问答服务实现类
 */
@Service
public class ExamQuestionAnswerServiceImpl implements ExamQuestionAnswerService {
    @Resource
    private ExamQuestionMapper examQuestionMapper;
    @Resource
    private ExamAnswerMapper examAnswerMapper;

    private final static Logger logger = LoggerFactory.getLogger(ExamQuestionAnswerServiceImpl.class);

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public RespBean<Integer> addExamQuestion(ExamQuestionDTO examQuestion) {
        logger.info("ExamQuestionDTO={}", JSON.toJSONString(examQuestion));
        RespBean<Integer> respBean = new RespBean<>();
        int questionCount = examQuestionMapper.addExamQuestion(examQuestion);
        if(questionCount==1){
            ExamAnswerDTO examAnswer = new ExamAnswerDTO();
            examAnswer.setQuestionId(examQuestion.getId());
            examAnswer.setCateName(examQuestion.getQuestionCate());
            examAnswer.setQuestionAnswer(examQuestion.getExamAnswer());
            examAnswerMapper.addExamAnswer(examAnswer);
            respBean.setStatus(200);
            respBean.setMsg("success");
            respBean.setData(1);
        } else {
            respBean.setStatus(500);
            respBean.setData(0);
            respBean.setMsg("failed");
        }
        return respBean;
    }

    @Override
    public RespBean<List<ExamQuestionDTO>> getExamQuestionsByCateName(String cateName) {
        logger.info("cateName={}", cateName);
        List<ExamQuestionDTO> examQuestionDTOS = examQuestionMapper.queryQuestionsByCateName(cateName);
        RespBean<List<ExamQuestionDTO>> respBean = new RespBean<>();
        respBean.setStatus(200);
        respBean.setMsg("success");
        respBean.setData(examQuestionDTOS);
        return respBean;
    }

    @Override
    public RespBean<ExamAnswerDTO> getExamAnswerByQuestionId(Integer questionId) {
        logger.info("questionId={}", questionId);
        ExamAnswerDTO examAnswerDTO = examAnswerMapper.getAnswerByQuestionId(questionId);
        RespBean<ExamAnswerDTO> respBean = new RespBean<>();
        respBean.setStatus(200);
        respBean.setMsg("success");
        respBean.setData(examAnswerDTO);
        return respBean;
    }
}
